<?php
namespace app\shop\controller\admin;

use app\admin\library\AdminController;
use app\shop\library\order\Order as O;

class Order extends AdminController{
    public function onIndex(){

        $this->pageTitle = '订单列表';
        $this->pageIcon = 'fa fa-print';
        $this->set('statusOption',O::STATUS_LIST);
        return $this->display();
    }


    public function onList(){
        $order_id = $this->post('order_id',$this->check()->type('string'));
        $status   = $this->post('status',$this->check()->type('string'));
        $page     = $this->post('page_current',$this->check()->type('int')->default(1));
        $pagesize =  30;

        $ordre = $this->model('Order');

        if ($order_id){
            $ordre->where('order_id','like','%'.$order_id.'%');
        }

        if ($status){
            $ordre->where('status',$status);
        }

        $orderGoods = $this->model('OrderGoods');

        $goodslistField = "select JSON_ARRAYAGG(JSON_OBJECT(
        'goods_id',goods_id,
        'title',title,
        'price',price,
        'sku_id',sku_id,
        'sku_name',sku_name,
        'picture',picture,
        'num',num
        )) ";
        $goodslistField .= 'from '.$orderGoods->getTable().' where '.$orderGoods->getTable().'.order_id = '.$ordre->getTable().'.order_id';
        $ordre->field('*,('.$goodslistField.') as goods');

        $list = $ordre->page($page,$pagesize)->order('created_at','desc')->getData();


        foreach ($list as $k=>$v){
            $list[$k]['goods'] = json_decode($v['goods'],true);
            $list[$k]['money_detail'] = json_decode($v['money_detail'],true);
        }

        return ['list'=>$list,'total'=>$ordre->total,'count'=>$ordre->pageCount];
    }

    public function onDetail(){
        $order_id = $this->post('id',$this->check()->type('string')->required());

        $order = $this->model('Order');
        $orderGoods = $this->model('OrderGoods');
        $memberCoupon = $this->model('MemberCoupon');


        $info = $order->getId($order_id);

        if (!$info){
            throw new \Exception('订单不存在');
        }

        $info['goods'] = $orderGoods->where('order_id',$order_id)->getData();
        $info['money_detail'] = json_decode($info['money_detail'],true);
        $info['coupon'] = $memberCoupon->where('order_id',$order_id)->getData();
        
        //获取优惠券
        return $info;
    }
}

